import 'package:flutter/material.dart';
import '../../models/product_template.dart';
import '../../services/database_helper.dart';
import '../../core/app_theme.dart';
import '../../core/snackbar_helper.dart';

class ProductTemplateScreen extends StatefulWidget {
  final int restaurantId;

  const ProductTemplateScreen({super.key, required this.restaurantId});

  @override
  State<ProductTemplateScreen> createState() => _ProductTemplateScreenState();
}

class _ProductTemplateScreenState extends State<ProductTemplateScreen> {
  List<ProductTemplate> _templates = [];
  List<bool> _selectedTemplates = [];
  bool _isLoading = true;

  @override
  void initState() {
    super.initState();
    _loadTemplates();
  }

  Future<void> _loadTemplates() async {
    try {
      final dbHelper = DatabaseHelper();
      final templates = await dbHelper.getProductTemplates();
      setState(() {
        _templates = templates;
        _selectedTemplates = List.filled(templates.length, false);
        _isLoading = false;
      });
    } catch (e) {
      print('加载商品模板失败: $e');
      SnackbarHelper.showError(context, '加载模板失败: $e');
      setState(() {
        _isLoading = false;
      });
    }
  }

  Future<void> _applySelectedTemplates() async {
    final selectedTemplates = <ProductTemplate>[];
    for (var i = 0; i < _templates.length; i++) {
      if (_selectedTemplates[i]) {
        selectedTemplates.add(_templates[i]);
      }
    }

    if (selectedTemplates.isEmpty) {
      SnackbarHelper.showError(context, '请至少选择一个商品模板');
      return;
    }

    try {
      final dbHelper = DatabaseHelper();
      
      // 检查是否已存在同名商品
      final existingProducts = await dbHelper.getProductsByRestaurant(widget.restaurantId);
      final existingProductNames = existingProducts.map((p) => p.name).toSet();
      
      final newTemplates = selectedTemplates.where((template) {
        return !existingProductNames.contains(template.name);
      }).toList();

      if (newTemplates.isEmpty) {
        SnackbarHelper.showError(context, '选中的模板在当前饭店中已存在');
        return;
      }

      // 如果有部分模板已存在，提示用户
      if (newTemplates.length < selectedTemplates.length) {
        final skippedCount = selectedTemplates.length - newTemplates.length;
        SnackbarHelper.showSuccess(context, '成功添加 ${newTemplates.length} 个商品，跳过 ${skippedCount} 个已存在的商品');
      } else {
        SnackbarHelper.showSuccess(context, '成功添加 ${newTemplates.length} 个商品');
      }
      
      await dbHelper.createProductsFromTemplates(widget.restaurantId, newTemplates);
      Navigator.of(context).pop(true);
    } catch (e) {
      SnackbarHelper.showError(context, '添加失败: $e');
    }
  }


  void _toggleAllSelection(bool selected) {
    setState(() {
      for (var i = 0; i < _selectedTemplates.length; i++) {
        _selectedTemplates[i] = selected;
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('选择商品模板', style: AppTheme.titleLarge),
        actions: [
          IconButton(
            icon: const Icon(Icons.done),
            onPressed: _applySelectedTemplates,
          ),
        ],
      ),
      body: _isLoading
          ? const Center(child: CircularProgressIndicator())
          : Column(
              children: [
                // 全选按钮
                Container(
                  padding: const EdgeInsets.all(16),
                  color: Colors.grey[100],
                  child: Row(
                    children: [
                      Checkbox(
                        value: _selectedTemplates.isNotEmpty && 
                               _selectedTemplates.every((selected) => selected),
                        onChanged: (value) => _toggleAllSelection(value ?? false),
                      ),
                      const Text('全选', style: AppTheme.bodyLarge),
                      const Spacer(),
                      Text(
                        '已选: ${_selectedTemplates.where((selected) => selected).length} 个',
                        style: AppTheme.bodyMedium,
                      ),
                    ],
                  ),
                ),
                // 模板列表
                Expanded(
                  child: ListView.builder(
                    itemCount: _templates.length,
                    itemBuilder: (context, index) {
                      final template = _templates[index];
                      return Card(
                        margin: const EdgeInsets.symmetric(horizontal: 12, vertical: 4),
                        child: CheckboxListTile(
                          title: Text(template.name, style: AppTheme.bodyLarge),
                          subtitle: Text(
                            '${template.defaultSpec} | ¥${template.defaultPrice.toStringAsFixed(2)}',
                            style: AppTheme.bodyMedium,
                          ),
                          value: _selectedTemplates[index],
                          onChanged: (value) {
                            setState(() {
                              _selectedTemplates[index] = value ?? false;
                            });
                          },
                        ),
                      );
                    },
                  ),
                ),
              ],
            ),
    );
  }
}